<template>
  <div>
    <a-modal
      v-model:visible="sVisible"
      :title="title"
      cancelText="取消"
      :okText="okText"
      :destroyOnClose="true"
      width="60%"
      @ok="submit"
      @cancel="cancel"
    >
      <template #footer>
        <a-button v-if="state.selectedRowKeys.length > 0" key="back" @click="cancel">取消</a-button>
        <a-button v-if="state.selectedRowKeys.length > 0" key="submit" type="primary" @click="submit">{{ okText }}</a-button>
      </template>
      <template v-if="searchForm.length > 0">
        <a-form
          ref="searchFormRef"
          :model="formState"
          :labelCol="{ span: 6 }"
          :wrapperCol="{ span: 18 }"
        >
          <a-row>
            <template v-for="item in searchForm" :key="item.key">
              <a-col :span="8">
                <a-form-item :label="item.label" :name="item.key">
                  <a-input
                    v-if="item.type === 'input'"
                    v-model:value="formState[item.key]"
                    :placeholder="item.placeholder"
                  />

                  <a-select
                    v-else-if="item.type === 'select'"
                    v-model:value="formState[item.key]"
                    :placeholder="item.placeholder"
                  >
                    <a-select-option
                      v-for="val in item.options"
                      :key="val.value"
                      :value="val.value"
                      >{{ val.label }}</a-select-option
                    >
                  </a-select>

                  <a-range-picker
                    v-else-if="item.type === 'rangePicker'"
                    v-model:value="formState[item.key]"
                  />
                </a-form-item>
              </a-col>
            </template>
            <a-col :span="8">
              <a-form-item label=" " :colon="false">
                <a-button type="primary" @click="onSubmit">查询</a-button>
                <a-button style="margin-left: 10px" @click="resetForm"
                  >重置</a-button
                >
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
      <a-input v-if="isinput" style="width:400px;marginRight:20px" v-model:value="inputName" placeholder="请输入" />
      <a-button v-if="isinput" type="primary" class="pro-query-button" @click="search">查询</a-button>
      <pro-table
        ref="tableRef"
        :fetch="fetch"
        :columns="defaultColumns"
        :operate="state.selection ? false : operate"
        :param="state.param"
        :pagination="state.isPagination == false ? false : pagination"
        :row-selection="state.selection ? { selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange } : false"
      >
      </pro-table>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, watch, nextTick } from "vue";
import { page } from "@/api/module/school";
import { cloneDeep } from "lodash";
import moment from "moment";

export default {
  name: "university",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => []
    },
    fetchAjax: {
      type: Function,
      default: page
    },
    title: {
      type: [String, Number],
      default: "选择学校"
    },
    searchParams: {
      type: Object,
      default: () => ({})
    },
    searchForm: {
      type: Array,
      default: () => []
    },
    isinput: {
      type: Boolean,
      default: false
    },
    // 是否分页
    isPagination: {
      type: Boolean,
      default: true
    },
    // 按钮名称
    okText: {
      type: String,
      default: '关闭'
    },
    // 是否多选
    selection: {
      type: Boolean,
      default: false
    },
    // 已选中的keys
    checkedKeys: {
      type: Array,
      default: () => []
    }
  },
  emits: ["update:visible", "selectUniversity"],

  setup(props, content) {
    const tableRef = ref(null);
    const sVisible = ref(props.visible);
    const searchFormRef = ref(null);
    // const isinput = ref(true)
    const pagination = {
      pageNum: 1,
      pageSize: 10
    };
    const state = reactive({
      selectedRowKeys: [],
      param: {},
      isPagination: props.isPagination,
      selection: props.selection || false,
      data: []
    });

    const defaultColumns = ref([]);

    const fetch = async (params) => {
      const response = await props.fetchAjax(params)
      if (response.code === 500) {
        return {
          data: [],
          total: 0
        };
      }
      if (props.checkedKeys && props.checkedKeys.length) {
        state.selectedRowKeys = props.checkedKeys
      }
      const data = response.data.record ||
          (Array.isArray(response.data) ? response.data : [])
      state.data = data
      return {
        data,
        total: response.data.total || undefined
      };
    };
    const resetForm = () => {
      searchFormRef.value.resetFields();
      onSubmit()
    };

    const formState = ref({});

    const onSubmit = () => {
      // 找出时间段类型 把值拆分
      const newObj = {
        ...formState.value
      };
      const timeTypeForm = props.searchForm.find(v => v.type === "rangePicker");
      if (timeTypeForm && newObj[timeTypeForm.key]) {
        newObj[timeTypeForm.outputValue[0]] = moment(
          newObj[timeTypeForm.key][0]
        ).format("YYYY-MM-DD HH:mm:ss");
        newObj[timeTypeForm.outputValue[1]] = moment(
          newObj[timeTypeForm.key][1]
        ).format("YYYY-MM-DD HH:mm:ss");
        delete newObj[timeTypeForm.key];
      }
      state.param = {
        ...state.param,
        ...newObj
      };
      // fetch(newObj)
    };

    watch(
      () => props.visible,
      () => {
        sVisible.value = props.visible;

        if (props.visible) {
          nextTick(() => {
            tableRef.value.fetch(
              props.isPagination ? { current: 1 } : undefined
            );
            props.searchForm.forEach(v => {
              formState[v.key] = null;
            });
          });
        }
      },
      { immediate: true }
    );

    watch(
      () => props.searchParams,
      () => {
        state.param = {
          ...state.param,
          ...props.searchParams
        };
      },
      { immediate: true, deep: true }
    );

    watch(
      () => props.columns,
      () => {
        defaultColumns.value = cloneDeep(props.columns);
      },
      { immediate: true }
    );

    /// 行操作
    const operate = [
      {
        label: "选择",
        event: function(record) {
          content.emit("selectUniversity", record);
          content.emit("update:visible", false);
        }
      }
    ];
    const inputName = ref("");
    // 搜索
    const search = ()=>{
      const params = {}
      params.name = inputName.value
      state.param = {
        ...params
      };
      // fetch(params)
    }
    const cancel = () => {
      // defaultColumns.value = []
      content.emit("update:visible", false);
    };
    const submit = () => {
      if (props.selection) {
        let keys = state.selectedRowKeys
        let arr = state.data.length && state.data.filter(item => keys.includes(item.id))
        content.emit("selectUniversity", { keys, data: arr});
      }
      cancel()
    };

    const onSelectChange = selectedRowKeys => {
      state.selectedRowKeys = selectedRowKeys;
    };
    return {
      state,
      operate,
      sVisible,
      tableRef,
      // isinput,
      inputName,
      search,

      pagination,
      fetch,
      cancel,
      defaultColumns,
      formState,
      submit,
      onSubmit,
      resetForm,
      searchFormRef,
      onSelectChange
    };
  }
};
</script>

<style scoped></style>
